﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using mshtml;
using System.Diagnostics;
using System.Reflection;

namespace AutoPageHelper
{

    public class ActionRecorder
    {

        public static ActionRecorder Default
        {
            get 
            { 
                if(_Instance == null)
                    _Instance = new ActionRecorder();
                return _Instance;
            }
        }
        public string RecordDirectory = "";
        public string ActionFile = "Actions.cs";
        public string Url = "";
        string _dir = "";
        static ActionRecorder _Instance;
        public void SavePage(IHTMLDocument doc)
        {
            string startupPath = Assembly.GetExecutingAssembly().Location;
            _dir = Path.GetDirectoryName(startupPath);
            if (!string.IsNullOrEmpty(RecordDirectory))
            {
                _dir = Path.Combine(_dir, RecordDirectory);
            }
            else
            {
                _dir = Path.Combine(_dir, "Record");
            }
            if (!Directory.Exists(_dir))
                Directory.CreateDirectory(_dir);
            string defaultFileName = "";
            if (doc == null)
                return;
            string url = (doc as IHTMLDocument2).url;
            string path = url.Replace("http://", "").Replace("file:///", "").Replace(":", "").Replace("\\", "/");
            int i = path.IndexOf('/');
            if (i < 1)
                return;
            else if (i >= path.Length - 1)
                defaultFileName = "index";
            
            string htmlFile = _dir + "\\" + path.Replace("/", "-").Replace("?", "@").Replace("*", "")
                + defaultFileName  + "_" + DateTime.Now.ToString("yyMMddHHmmssfff") + ".htm";
            
            if (File.Exists(htmlFile))
                htmlFile = htmlFile.Substring(0, htmlFile.Length - 4) + "#" + (new Random()).Next(1000).ToString("D3") + ".htm";

            if (doc == null)
                return;
            StreamWriter sw = new StreamWriter(htmlFile);
            sw.WriteLine("<!-- " + url + " -->");
            sw.Write((doc as IHTMLDocument3).documentElement.outerHTML);
            sw.Close();
            string title = (doc as IHTMLDocument2).title;
            if (string.IsNullOrEmpty(title))
                title = "[no title]";
            string action = "DocumentComplete:{" + title + ":=" + url + "}";
            SaveAction(action);
        }


        public void SaveAction(string actionText)
        {
            ParserFactory ap = new ParserFactory();
            string script = ap.ParseAction(actionText);
            if (!string.IsNullOrEmpty(Url) && !string.IsNullOrEmpty(script))
            {
                script += "// url:" + Url;
                Url = string.Empty;
            }
            Save(script);
        }

        private void Save(string text)
        {
            if (string.IsNullOrEmpty(text))
                return;
            StreamWriter swAction = new StreamWriter(Path.Combine(_dir, ActionFile), true);
            swAction.WriteLine(text);// + "//ts:" + DateTime.Now.ToString(" yyyy-MM-dd HH:mm:ss:fff"));
            swAction.Close();
        }
    
    }
}
